<template>
  <div class="myCourse-container">
    <div class="join-container">
      <el-button type="warning" @click="joinGroupDialogVisible = true" style="margin-right: 20px">
        + 加入小组
      </el-button>
      <!--加入小组的弹窗-->
      <el-dialog title="输入小组号:" :visible.sync="joinGroupDialogVisible" width="40%" @close="handleClose">
        <el-input v-model="joinGroupParams.groupId"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="joinGroup()">确认加入</el-button>
        </span>
      </el-dialog>

      <el-button type="primary" @click="courseDialogVisible = true">
        + 加入新课程
      </el-button>
      <!--加入课程的弹窗-->
      <el-dialog title="输入课程暗号:" :visible.sync="courseDialogVisible" width="40%" @close="handleClose">
        <el-input v-model="joinForm.courseId"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="joinCourse()">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <el-table :data="tableData" class="data_table">
      <el-table-column prop="courses.id" label="课程编号" width="120px">
      </el-table-column>
      <el-table-column prop="courses.teacherName" label="教师姓名">
      </el-table-column>
      <el-table-column prop="courses.courseType" label="课程类型">
      </el-table-column>
      <el-table-column prop="courses.courseName" label="课程名称">
      </el-table-column>
      <el-table-column prop="courses.scoreRatio" label="课程评分占比">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="text" size="small" class="delBut" @click="createGroupDialog(scope.row.id)">
            创建小组
          </el-button>
          <el-button type="text" size="small" class="delBut" @click="getGroupMessage(scope.row.courseId)">
            小组信息
          </el-button>
          <el-button type="text" size="small" class="delBut" @click="viewAssignments(scope.row)">
            课程作业
          </el-button>
          <el-button type="text" size="small" class="delBut" @click="myAssignments()">
            我的作业
          </el-button>
          <el-button type="text" size="small" class="delBut" @click="quitCourseHandle(scope.row.id)">
            退出课程
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <!-- 查看小组对话框组件 -->
      <el-dialog :visible.sync="isGroupMessageVisible" title="小组列表" width="30%">
        <div style="font-size: 20px;"><span>小组编号</span>{{ groupIdInCourse }}</div>
        <group-list :group="ownGroupList"></group-list>
        <span slot="footer" class="dialog-footer">
          <el-button type="success" @click="" style="margin-right: 36px">小组作业</el-button>
          <el-button type="danger" @click="quitGroup()" style="margin-right: 36px">退出组</el-button>
          <el-button @click="isGroupMessageVisible = false">关闭</el-button>
        </span>
      </el-dialog>

      <!--创建组的弹窗-->
      <el-dialog title="创建小组:" :visible.sync="createGroupDialogVisible" width="40%" @close="handleClose">
        <el-input v-model="createGroupForm.leader" placeholder="请输入组长姓名(小组昵称)" style="margin-bottom: 36px"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="createGroup()">创建组</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>

import {
  getGradeRecordsAPI_Student,
  joinCourseAPI_Student
} from "@/api/student/courses";
import { getUserIDLocalStorage } from "@/utils/utilLocalStorage";
import GroupList from "@/views/Student/Lesson/Mine/groupList.vue";
import {
  createGroupsAPI_Student, exitGroupByGroupIdAndStuIdAPI,
  getGroupsMessageAPI, getStuMessageByGroupIdAPI,
  joinGroupsAPI_Student
} from "@/api/student/groups";
import { DATA_OK_NUM } from "@/constants/KEY";
import { deleteSudentCourseRecordAPI } from '@/api/score';
import { addMemberAPI } from '@/api/groupMember'


export default {
  name: 'manage',
  components: { GroupList },
  data() {
    return {
      courseDialogVisible: false,
      joinGroupDialogVisible: false,
      createGroupDialogVisible: false,
      isGroupMessageVisible: false,
      successCode: '',
      group: [
        { id: 1, name: '前端开发', avatar: '' },
        { id: 2, name: '后端开发', avatar: '' },
      ],
      ownGroupList: [],
      groupIdInCourse: '', // 该课程下学生所在的组id
      joinForm: {
        studentId: '',
        courseId: ''
      },
      createGroupForm: {
        groupId: '',
        courseId: '',
        leader: '',
        studentId: ''
      },
      tableData: [],
      queryParams: {
        assignmentId: null,
        courseId: null,
        teacherId: null
      },
      joinGroupParams: {
        groupId: '',
        studentId: ''
      },
      delGroupForm: {
        groupId: '',
        studentId: ''
      }
    }
  },
  mounted() {
    this.getCourses()
    this.createGroupForm.studentId = getUserIDLocalStorage()
  },
  methods: {
    handleClose() {
      // 加入小组的弹窗
      this.joinGroupDialogVisible = false

      // 清除加入课程的数据
      this.courseDialogVisible = false
      this.joinForm.courseId = ''

      // 清除加入、创建组的数据
      this.createGroupDialogVisible = false
      this.createGroupForm = {
        groupId: '',
        courseId: '',
        leader: ''
      }
    },
    // 加入课程
    joinCourse() {
      this.joinForm.studentId = getUserIDLocalStorage()
      joinCourseAPI_Student(this.joinForm).then((res) => {
        this.$message.success('加入课程成功！')
        this.handleClose()
        this.getCourses()
      }).catch(() => {
        this.$message.error('加入课程失败，请检查课程暗号！')
      })
    },
    // 获取学生的所有课程
    getCourses() {
      getGradeRecordsAPI_Student(getUserIDLocalStorage()).then((res) => {
        // console.log('获取学生个人的所有课程: ',res)
        // 循环获取教师id每一门课程对应的教师名字
        this.tableData = res.data
      })
    },
    // 加入小组对话框
    createGroupDialog(courseId) {
      // 首先查询是否已经加入了小组,加入了则不允许创建或加入,对话框不显示并且提示不允创建
      this.createGroupDialogVisible = true

      // 取课程id,用于创建该门课程下的小组
      this.createGroupForm.courseId = courseId
    },
    // 发送加入组请求
    joinGroup() {
      this.joinGroupParams.studentId = getUserIDLocalStorage()
      joinGroupsAPI_Student(this.joinGroupParams).then((res) => {
        // console.log('加入组请求返回：',res)
        if (res.data === DATA_OK_NUM) {
          this.$message.success('加入小组成功！')
        } else {
          this.$message.error('加入小组失败，请检查是否正确或是在该门课程已经加入了小组！')
        }
      }).catch(() => {
        this.$message.error('加入小组失败，请检查小组号是否存在！')
      })
      this.handleClose()
    },
    // 发送创建组请求
    createGroup() {
      // 课程id
      this.createGroupForm.studentId = getUserIDLocalStorage()
      createGroupsAPI_Student(this.createGroupForm).then((res) => {
        // console.log('创建小组successCode：',res.data.successCode)
        if (res.data.successCode === DATA_OK_NUM) {
          this.$message.success('创建小组成功！')
        } else {
          this.$message.error('创建小组失败，请检查是否在该门课程已经加入了小组！')
        }
      }).catch(() => {
        this.$message.error('创建组失败！')
      })
      this.handleClose()
    },

    // 查看小组信息
    getGroupMessage(courseId) {
      getGroupsMessageAPI(getUserIDLocalStorage()).then((res) => {
        // console.log('查该学生加入的组：',res.data)
        if (res.data === null || res.data.length === 0) {
          this.$message.error('暂未加入任何组，无法查看小组信息！')
          return
        }
        // 该学生存在加入至少一个组的情况下：
        this.ownGroupList = res.data
        this.groupIdInCourse = this.getOwnGroupByCourseId(courseId)
        getStuMessageByGroupIdAPI(this.groupIdInCourse).then((res) => {
          // console.log('获取该课程该学生所在的小组：',res)
          if (res.data === null || res.data.length === 0) {
            this.$message.error('小组数据为空！')
            return
          }
          this.ownGroupList = res.data
          this.isGroupMessageVisible = true
        }).catch(() => {
          this.$message.error('该课程未加入小组，无法查看小组信息！')
        })
      }).catch(() => {
        this.$message.error('请求异常！')
      })
    },
    // 通过已经获取该学生的所有组信息，截取某个课程下的组学生信息
    getOwnGroupByCourseId(courseId) {
      for (let i = 0; i < this.ownGroupList.length; i++) {
        const ownGroup = this.ownGroupList[i];
        if (ownGroup.groups.courseId === courseId) {
          // console.log('该课程下该学生所在组的id：', ownGroup.groupId);
          return ownGroup.groupId;
        }
      }
      return '';
    },

    // 退出小组按钮(小组信息下)
    quitGroup(courseId) {
      // 二次确认
      this.$confirm('确认退出该小组?').then(async () => {
        // 根据小组id与学生id退出组
        this.delGroupForm.groupId = this.ownGroupList[0].groupId
        this.delGroupForm.studentId = getUserIDLocalStorage()
        exitGroupByGroupIdAndStuIdAPI(this.delGroupForm).then((res) => {
          // console.log('学生退出组：',res)
          if (res.data.successCode === DATA_OK_NUM) {
            this.$message.error('退出组失败！')
          }
          this.$message.success('退出组成功！')
          this.isGroupMessageVisible = false
        }).catch(() => {
          this.$message.error('请求异常！')
        })
      })
    },

    // 根据课程id查看作业
    viewAssignments(row) {
      getGroupsMessageAPI(getUserIDLocalStorage()).then((res) => {
        // console.log('查该学生加入的组：',res.data)
        if (res.data === null || res.data.length === 0) {
          this.$message.error('暂未加入任何组，无法查看小组信息！')
          return
        }
        // 该学生存在加入至少一个组的情况下：
        this.ownGroupList = res.data
        this.groupIdInCourse = this.getOwnGroupByCourseId(row.courseId)
        this.$router.push({
          path: '/student/viewAssignment',
          query: {
            courseId: row.courseId,
            groupIdInCourse: this.groupIdInCourse
          }
        });

      });


      // // console.log('查看作业row: ',row)
      // this.queryParams.courseId = row.courseId
      // groupIdInCourse
      // this.$router.push('/student/viewAssignment?courseId=' + this.queryParams.courseId)
    },
    // 我的作业-根据学生id查询学生提交过的作业
    myAssignments() {
      this.$router.push({
        path: '/student/myAssignment',
        // query: {
        //   courseId: row.courseId,
        //   groupIdInCourse: this.groupIdInCourse
        // }
      });
    },
    // 退出课程
    quitCourseHandle(gradeRecordId) {
      this.$confirm('确认删除该学生, 是否继续?', '学生关于此门课程的信息被一并删除。确定删除？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.quitCourse(gradeRecordId)
        // deleteSudentCourseRecordAPI(gradeRecordId)
      })

    },
    async quitCourse(gradeRecordId) {
      try {
        const res = await deleteSudentCourseRecordAPI(gradeRecordId)
        // 处理资源的代码
        if (res.code === 200) {
          this.getCourses()
          this.$message.success(res.message)
        }
        // 处理资源的代码
      } catch (error) {
        // 处理异常的代码
        console.error('Error fetching delete:', error);
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.join-container {
  margin-right: 18px;
  margin-bottom: 15px;
  display: flex;
  /* 开启Flexbox布局 */
  align-items: center;
  /* 垂直居中 */
  justify-content: flex-end;
  /* 水平方向上靠左对齐 */
}
</style>
